package com.kai.kaiMybatis.sqlsession;

import com.kai.config.Function;
import com.kai.config.MapperBean;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author kai
 * @version 1.0
 * @date 2024/7/30
 * @Description
 */
@SuppressWarnings("all")
public class kaiConfiguration {

    //属性-类的加载器
    private static ClassLoader classLoader = ClassLoader.getSystemClassLoader();

    //读取xml文件信息，并处理
    public Connection build(String resource) {

        Connection connection = null;

        try {
            //先加载配置文件，获取到对应的inputstream
            InputStream stream = classLoader.getResourceAsStream(resource);

            //解析xml文件
            SAXReader reader = new SAXReader();


            Document document = reader.read(stream);

            //获取到kai_mybatis.xml的根元素<database>
            Element rootElement = document.getRootElement();

            System.out.println("根元素=" + rootElement);

            connection = evalDataSource(rootElement);
            //根据解析返回连接

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return connection;

    }

    //方法会解析xml文件。并返回一个connection
    private Connection evalDataSource(Element node) {

        if (!"database".equals(node.getName())) {
            throw new RuntimeException("root节点应该是database");
        }

        String driverClassName = null;
        String url = null;
        String username = null;
        String password = null;

        //遍历子节点
        for (Object item : node.elements("property")) {

            Element i = (Element) item;

            String name = i.attributeValue("name");
            String value = i.attributeValue("value");

            //判断name和value是否为空
            if (name == null || value == null) {
                throw new RuntimeException("name和value值不可以为空");
            }

            switch (name) {
                case "url":
                    url = value;
                    break;
                case "username":
                    username = value;
                    break;
                case "password":
                    password = value;
                    break;
                case "driverClassName":
                    driverClassName = value;
                    break;

                default:
                    throw new RuntimeException("属性名不匹配");
            }


        }
        Connection connection = null;

        try {
            Class.forName(driverClassName);

            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;//返回Connection

    }

    //读取XXXMapper.xml,能够创建MapperBean对象
    //path为xml文件路径
    public MapperBean readMapperxml(String path) {
        MapperBean mapperBean = new MapperBean();
        try {
            //获取到xml文件对应的输入流
            InputStream resourceAsStream = classLoader.getResourceAsStream(path);

            SAXReader reader = new SAXReader();

            //获取文档
            Document document = reader.read(resourceAsStream);

            //获取到根节点
            Element rootElement = document.getRootElement();

            //System.out.println("rootElement= " + rootElement);

            //获取到nameSpqce
            String namespace = rootElement.attributeValue("namespace").trim();
            //设置MapperBean
            mapperBean.setInterfaceName(namespace);

            //得到root的迭代器-可以遍历他的子节点/子元素  比如多个sql语句
            Iterator iterator = rootElement.elementIterator();

            List<Function> list = new ArrayList<>();

            //
            while (iterator.hasNext()) {

                /* <select id="selectonebyId" parameterType="Integer" resultType="com.kai.entity.Monster">
                     select * from monster where id =?
                    </select>
                  */
                Element e = (Element) iterator.next();
                //System.out.println(e);
                Function function = new Function();

                String id = e.attributeValue("id").trim();
                String sqlType = e.getName().trim();
                String parameterType = e.attributeValue("parameterType").trim();

                //这里拿到的是 resultType==com.kai.entity.Monster
                String resultType = e.attributeValue("resultType").trim();
                //System.out.println("resultType==" + resultType);
                String sql = e.getText().trim();

                //封装
                function.setSql(sql);

                function.setFuncName(id);
                function.setSqlType(sqlType);
                function.setParameterType(parameterType);

                Object newInstance = Class.forName(resultType).newInstance();
                function.setResulttype(newInstance);

                list.add(function);

            }

            mapperBean.setFunctions(list);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return mapperBean;

    }

}
